package com.project.study.farming.common.utils;

import com.project.study.farming.base.entity.po.CropsPo;
import com.project.study.farming.base.entity.po.PlantPo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 植物成长
 * @since 2020-05-17
 */
@Service
public class GroupUpManager {

    @Autowired
    private BeanMapper beanMapper;

    private ThreadGroup group = new ThreadGroup("group-up");

    private ScheduledExecutorService poolService = new ScheduledThreadPoolExecutor(2, r -> new Thread(group, r));

    @PostConstruct
    private void groupUp(){
        poolService.scheduleAtFixedRate(() -> {
        List<PlantPo> plants = this.beanMapper.selectList(PlantPo.class);
        plants.forEach(this :: up);
        }, 0, 10, TimeUnit.MINUTES);
    }

    private void up(PlantPo plant){
        CropsPo crop = this.beanMapper.selectOne(CropsPo.class, String.format("id = %d", plant.getCropsId()));
        LocalDateTime createTime = plant.getCreateTime();
        LocalDateTime now = LocalDateTime.now();
        Duration dur = Duration.between(createTime, now);
        Integer status = plant.getCropsStatus();
        long hours = dur.toHours();
        if(status == 106001 && hours > 24){
            plant.setCropsStatus(106002);
        }else if(status == 106002 && hours >= crop.getMaturity() * 24){
            plant.setCropsStatus(106003);
        }
        this.beanMapper.updateById(plant);
    }
}
